package pl.edu.pw.perg.compinfodb.command;

import java.util.LinkedList;
import java.util.List;

import org.springframework.richclient.command.support.AbstractActionCommandExecutor;

import pl.edu.pw.perg.compinfodb.datamodel.IConditionChangeListener;
import pl.edu.pw.perg.compinfodb.datamodel.IPhysicalElementSelectionListener;
import pl.edu.pw.perg.compinfodb.datamodel.IRefreshListener;
import pl.edu.pw.perg.compinfodb.datamodel.IStructureTreeSelectionListener;
import pl.edu.pw.perg.compinfodb.datamodel.ModulesHistoryTableModel;
import pl.edu.pw.perg.compinfodb.datamodel.StructureHistoryTableModel;
import pl.edu.pw.perg.compinfodb.entities.PhysicalElement;
import pl.edu.pw.perg.compinfodb.entities.VirtualElement;
import pl.edu.pw.perg.compinfodb.manager.IComplexElementManager;
import pl.edu.pw.perg.compinfodb.manager.IPhysicalElementManager;
import pl.edu.pw.perg.compinfodb.manager.IVirtualElementManager;

public class InsertElementCommandExecutor extends AbstractActionCommandExecutor implements IPhysicalElementSelectionListener, IStructureTreeSelectionListener, IConditionChangeListener {

	private VirtualElement ve;
	private PhysicalElement pe;
	private IComplexElementManager complexElementManager;
	private boolean nonMarked;
	private List<IRefreshListener> refreshListeners = new LinkedList<IRefreshListener>();
	private ModulesHistoryTableModel modulesHistory;
	private StructureHistoryTableModel structureHistory;
	
	@Override
	public void execute() {
//		PhysicalElement previousPe = (PhysicalElement) ve.getPhysicalElement();
//		VirtualElement previousVe = (VirtualElement) pe.getVirtualElement();
//		
//		complexElementManager.unboundElements(previousVe, previousPe);
		complexElementManager.boundElements(ve, pe);
		
		for (IRefreshListener l : refreshListeners) {
			l.refresh();
		}
		setEnabled(false);
		nonMarked = false;
		modulesHistory.inserted(ve, pe);
		structureHistory.inserted(pe);
	}



	public void setVe(VirtualElement ve) {
		this.ve = ve;
	}

	public void setPe(PhysicalElement pe) {
		this.pe = pe;
	}

	public void selectionChanged(PhysicalElement ce) {
		this.pe = ce;
		if(ve != null && pe != null && nonMarked)
			setEnabled(true);
		else
			setEnabled(false);
	}

	public void selectionChanged(VirtualElement ve) {
		this.ve = ve;
		
	}



	public void setComplexElementManager(
			IComplexElementManager complexElementManager) {
		this.complexElementManager = complexElementManager;
	}



	public void conditionChanged(boolean conditionValue) {
		nonMarked = conditionValue;
		
	}
	public void addRefreshListener(IRefreshListener l){
		refreshListeners.add(l);
	}



	public void setModulesHistory(ModulesHistoryTableModel modulesHistory) {
		this.modulesHistory = modulesHistory;
	}



	public void setStructureHistory(StructureHistoryTableModel structureHistory) {
		this.structureHistory = structureHistory;
	}
}
